"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 集群重启时，备节点网络链路闪断
Create At   : 2021/09/23
@zou_jialiang0505328126
Description :
    1.注入网络链路闪断
    2.停止集群
    3.重启集群
    4.查询集群状态
Expect      :
    1.成功
    2.成功
    3.可能因为网络中断失败
    4.正常
History     :
    modified：2022-5-25 by 5328113;优化用例，注入网卡故障后增加等待，保证后续操作在无故障场景下执行
"""

import os
import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node


class NetWork(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.sta1_root = Node(node='Standby1Root')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')

        self.log.info("----获取网卡名----")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.sta1_root.sh(network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.network_card = ''
        for network_card_item in network_card_list:
            if self.sta1_dbuser.db_host in network_card_item:
                self.network_card = network_card_item.split(':')[0].strip()
                self.log.info(self.network_card)

    def test_main(self):
        try:
            self.text1 = '----step1: 注入网络链路闪断 expect:成功----'
            self.log.info(self.text1)
            time.sleep(2)
            inject_command = f" rNetLink_flash " \
                f"(repeat,duration,interval,dev) " \
                f"values (50,2,5,{self.network_card})"
            self.cfe_thread = ComThread(
                self.com.cfe_inject, args=(self.sta1_root,
                                           inject_command,))
            self.cfe_thread.setDaemon(True)
            self.cfe_thread.start()
            self.start_time = time.time()

            text = '----step2: 停止集群 expect:成功----'
            self.log.info(text)
            result = self.primary_sh.stopDbCluster()
            self.assertTrue(result, '执行失败' + text)

            text = '----step3: 启动集群 expect:可能因为网络中断失败----'
            self.log.info(text)
            start_result = self.primary_sh.startDbCluster()
            if start_result:
                self.assertTrue(start_result, '执行失败' + text)
        finally:
            self.log.info('----获取step1故障结果----')
            self.cfe_thread.join(500)
            result = self.cfe_thread.get_result()
            self.log.info(result)
            flg1 = self.constant.cfe_inject_netflash_success_msg in result \
                   or 'Determining IP information' in result
            self.assertTrue(flg1, '执行失败' + self.text1)
            time.sleep(5)

        self.log.info('----等待故障结束（2+5）*50s+7s----')
        self.end_time = time.time()
        self.log.info('start_time:' + time.strftime(
            '%Y-%m-%d %H:%M:%S', time.localtime(int(self.start_time))) +
                      ';end_time:' + time.strftime(
            '%Y-%m-%d %H:%M:%S', time.localtime(int(self.end_time))))
        if self.end_time - self.start_time < 357:
            time.sleep(357 - self.end_time + self.start_time)

        if not start_result:
            text = '----如果因为网络中断，step3重启集群失败，进行重启----'
            self.log.info(text)
            result = self.primary_sh.startDbCluster()
            self.assertTrue(result, '执行失败' + text)

        text = '----step4: 查询集群状态 expect:正常----'
        self.log.info(text)
        result = self.primary_sh.getDbClusterStatus("status")
        self.assertTrue(result, '执行失败' + text)

    def tearDown(self):
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
